﻿using System.Dynamic;

namespace Eswat
{
	/// <summary>
	/// Base test services accessor, requires an implementation.
	/// </summary>
	public abstract class TestServiceAccessorBase : DynamicObject
	{
		/// <summary>
		/// Provides the implementation for operations that get member values. Classes derived from the <see cref="T:System.Dynamic.DynamicObject"/> class can override this method to specify dynamic behavior for operations such as getting a value for a property.
		/// </summary>
		/// <param name="binder">Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member on which the dynamic operation is performed. For example, for the Console.WriteLine(sampleObject.SampleProperty) statement, where sampleObject is an instance of the class derived from the <see cref="T:System.Dynamic.DynamicObject"/> class, binder.Name returns "SampleProperty". The binder.IgnoreCase property specifies whether the member name is case-sensitive.</param>
		/// <param name="result">The result of the get operation. For example, if the method is called for a property, you can assign the property value to <paramref name="result"/>.</param>
		/// <returns>
		/// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a run-time exception is thrown.)
		/// </returns>
		public override bool TryGetMember(
			GetMemberBinder binder, out object result)
		{
			result = (ITestService)null;

			// Converting the property name to lowercase
			// so that property names become case-insensitive.
			string name = binder.Name;

			// If the property name is found in a service locator,
			// set the result parameter to the property value and return true.
			// Otherwise, return false.
			try
			{
				result = this.GetService<ITestService>(name);

				return true;
			}
			catch
			{
				result = (ITestService)null;
				return false;
			}
		}

		/// <summary>
		/// Gets the test service using the specified <paramref name="key"/>.
		/// </summary>
		/// <typeparam name="T">The type of service to obtain.</typeparam>
		/// <param name="key">The unique test service key.</param>
		/// <returns>An instance of the test service, if it exists.</returns>
		protected abstract T GetService<T>(string key) where T : ITestService;
	}
}
